var express = require('express');
var router = express.Router();
var PostModel = require('../models/posts');
var UserModel = require('../models/users')
var CommentModel = require('../models/comments');
var checkLogin = require('../middlewares/check').checkLogin;
var sha1 = require('sha1');
// GET /posts 所有用户或者特定用户的文章页
//   eg: GET /posts?author=xxx
router.get('/', function(req, res, next) {
  var author = req.query.author;

  PostModel.getPosts(author)
    .then(function (posts) {
      req.session.user = req.session.user;
      res.render('posts', {
        posts: posts,
        user: req.session.user,
        url: req.path + 'posts',
      });
    })
    .catch(next);
});

// GET /posts/create 发表文章页
router.get('/create', checkLogin, function(req, res, next) {
  res.render('create', {
    url: req.path,
  });
});

// GET /posts/usersettings 个人设置页
router.get('/usersettings', checkLogin, function(req, res, next) {
  var user = req.session.user;
  var name = user.name;
  var avatar = user.avatar;
  var id = user._id;
  var gender = user.gender;
  if(gender == 'm'){
    gender = 'Male';
  }else if(gender =='f'){
    gender = 'Female';
  }else{
    gender = '保密';
  }
  var bio = user.bio;
  var createTime = user.created_at;
  var ip = req.headers['x-forwarded-for'] ||
  req.connection.remoteAddress ||
  req.socket.remoteAddress ||
  req.connection.socket.remoteAddress;

  res.render('usersettings', {
    url: req.path,
    name: name,
    avatar: avatar,
    ip: ip,
    id: id,
    gender: gender,
    time: createTime,
    bio: bio,
  });
});

// POST /posts 发表一篇文章
router.post('/', checkLogin, function(req, res, next) {
  var author = req.session.user._id;
  var title = req.fields.title;
  var content = req.fields.content;

  // 校验参数
  try {
    if (!title.length) {
      throw new Error('请填写标题');
    }
    if (!content.length) {
      throw new Error('请填写内容');
    }
  } catch (e) {
    req.flash('error', e.message);
    return res.redirect('back');
  }

  var post = {
    author: author,
    title: title,
    content: content,
    pv: 0
  };

  PostModel.create(post)
    .then(function (result) {
      // 此 post 是插入 mongodb 后的值，包含 _id
      post = result.ops[0];
      req.flash('success', '发表成功');
      // 发表成功后跳转到该文章页
      res.redirect(`/posts/${post._id}`);
    })
    .catch(next);
});

// GET /posts/:postId 单独一篇的文章页
router.get('/:postId', function(req, res, next) {
  var postId = req.params.postId;
  
  Promise.all([
    PostModel.getPostById(postId),// 获取文章信息
    CommentModel.getComments(postId),// 获取该文章所有留言
    PostModel.incPv(postId)// pv 加 1
  ])
  .then(function (result) {
    var post = result[0];
    var comments = result[1];
    if (!post) {
      throw new Error('该文章不存在');
    }

    res.render('post', {
      post: post,
      comments: comments,
      url: req.path
    });
  })
  .catch(next);
});


// GET /posts/:postId/edit 更新文章页
router.get('/:postId/edit', checkLogin, function(req, res, next) {
  var postId = req.params.postId;
  var author = req.session.user._id;
  
  PostModel.getPostById(postId)
    .then(function (post) {
      if (!post) {
        throw new Error('该文章不存在');
      }
      if (author.toString() !== post.author._id.toString()) {
        throw new Error('权限不足');
      }
      res.render('edit', {
        post: post,
        url: req.path,
      });
    })
    .catch(next);
});

// POST /posts/:postId/edit 更新一篇文章
router.post('/:postId/edit', checkLogin, function(req, res, next) {
  var postId = req.params.postId;
  var author = req.session.user._id;
  var title = req.fields.title;
  var content = req.fields.content;

  PostModel.updatePostById(postId, author, { title: title, content: content })
    .then(function () {
      req.flash('success', '编辑文章成功');
      // 编辑成功后跳转到上一页
      res.redirect(`/posts/${postId}`);
    })
    .catch(next);
});

// GET /posts/:postId/edit 个人设置页
router.get('/:userId/editsettings', checkLogin, function(req, res, next) {
  var userid_1 = req.params.userId;
  var userid_2 = req.session.user._id;
  var user = req.session.user;
  var name = user.name;
  var bio = user.bio;
  res.render('editsettings', {
    // post: post,
    url: req.path,
    userid: userid_1,
    id: userid_2,
    name: name,
    bio: bio,
  });
});

// POST /posts/:postId/edit 更新个人设置
router.post('/:userId/editsettings', checkLogin, function(req, res, next) {
  var userid = req.params.userId;
  var id_1 = req.session.user._id;
  // var id_2 = req.fields.id;
  var name = req.fields.name;
  var password = req.fields.password;
  var repassword = req.fields.repassword;
  var gender = req.fields.gender;
  var bio = req.fields.bio;
  if (!(name.length >= 1 && name.length <= 10)) {
    req.flash('error', '名字请限制在 1-10 个字符');
    res.redirect('back');
  }
  if (['m', 'f', 'x'].indexOf(gender) === -1) {
    req.flash('error', '性别只能是 m、f 或 x');
    res.redirect('back');
  }
  if (!(bio.length >= 1 && bio.length <= 30)) {
    req.flash('error', '个人简介请限制在 1-30 个字符');
    res.redirect('back');
  }
  if (password.length < 6) {
    req.flash('error', '密码至少 6 个字符');
    res.redirect('back');
  }
  if (password !== repassword) {
    req.flash('error', '两次输入密码不一致');
    res.redirect('back');
  }
  password = sha1(password);
  var user = {
    id: id_1,
    name: name,
    password: password,
    gender: gender,
    bio: bio,
  };
  UserModel.updateUserSettings(user,req)
  .then(function (result) {
    // // 将用户信息存入 session
    //  delete user.password;
    // req.session.user = null;
    // req.session.user = user;
    // 写入 flash
    req.flash('success', '修改个人资料成功，请重新登录。');
    // 跳转到首页
    res.redirect('/posts');
  })
  .catch(function (e) {
    // 用户名被占用则跳回注册页，而不是错误页
    if (e.message.match('E11000 duplicate key')) {
      req.flash('error', '用户名已被占用');
      return res.redirect('back');
    }
    next(e);
  });
  // PostModel.updatePostById(id, author, { title: title, content: content })
  //   .then(function () {
  //     req.flash('success', '更新个人设置成功');
  //     // 编辑成功后跳转到上一页
  //     res.redirect(`/posts`);
  //   })
  //   .catch(next);
});

// GET /posts/:postId/remove 删除一篇文章
router.get('/:postId/remove', checkLogin, function(req, res, next) {
  var postId = req.params.postId;
  var author = req.session.user._id;

  PostModel.delPostById(postId, author)
    .then(function () {
      req.flash('success', '删除文章成功');
      // 删除成功后跳转到主页
      res.redirect('/posts');
    })
    .catch(next);
});

// POST /posts/:postId/comment 创建一条留言
router.post('/:postId/comment', checkLogin, function(req, res, next) {
  var author = req.session.user._id;
  var postId = req.params.postId;
  var content = req.fields.content;
  var comment = {
    author: author,
    postId: postId,
    content: content
  };

  CommentModel.create(comment)
    .then(function () {
      req.flash('success', '留言成功');
      // 留言成功后跳转到上一页
      res.redirect('back');
    })
    .catch(next);
});

// GET /posts/:postId/comment/:commentId/remove 删除一条留言
router.get('/:postId/comment/:commentId/remove', checkLogin, function(req, res, next) {
  var commentId = req.params.commentId;
  var author = req.session.user._id;

  CommentModel.delCommentById(commentId, author)
    .then(function () {
      req.flash('success', '删除留言成功');
      // 删除成功后跳转到上一页
      res.redirect('back');
    })
    .catch(next);
});

module.exports = router;
